import React, { Component } from "react";

export default class Select extends Component {
  constructor() {
    super();
    this.state = { //把树形结构 降维处理
      cityList: [],
      townList: [],
      list: [
        {
          id: 1,
          name: "湖北",
          list: [
            {
              id: 11,
              name: "武汉",
              list: [
                { id: 111, name: "洪山" },
                { id: 112, name: "江夏" },
              ],
            },
            {
              id: 12,
              name: "荆州",
              list: [
                { id: 121, name: "沙市" },
                { id: 122, name: "松滋" },
              ],
            },
          ],
        },
        {
          id: 2,
          name: "河南",
          list: [
            {
              id: 21,
              name: "郑州",
              list: [
                { id: 211, name: "新郑" },
                { id: 212, name: "金水" },
              ],
            },
            {
              id: 22,
              name: "洛阳",
              list: [
                { id: 221, name: "洛阳的区一" },
                { id: 222, name: "洛阳的区二" },
              ],
            },
          ],
        },
      ],
    };
  }
  provinceChange = (id) => {
    //console.log(typeof id);
    if (id) {
      //省份的编号  跟进省份的编号 找到对应的城市
      this.setState({
        townList:[],
        cityList: this.state.list.filter((item) => item.id == id)[0]["list"], //filter返回的是一个集合(数组) 编号是唯一的  取出来的对象  要是的是对象的list属性
      });
    } else {
      this.setState({
        cityList: [],
        townList:[]
      });
    }
  };
  cityChange = (id) => {
    if (id) {
      this.setState({
        townList: this.state.cityList.filter((item) => item.id == id)[0].list,
      });
    }else{
      this.setState({
        townList:[]
      })
    }
  };

  render() {
    return (
      <div>
        <select
          onChange={(e) => {
            this.provinceChange(e.target.value);
          }}
        >
          <option value="">请选择省份</option>
          {this.state.list.map((item) => {
            return (
              <option key={item.id} value={item.id}>
                {item.name}
              </option>
            );
          })}
        </select>
        <select
          onChange={(e) => {
            this.cityChange(e.target.value);
          }}
        >
          <option value="">请选择城市</option>
          {this.state.cityList.map((item) => {
            return (
              <option key={item.id} value={item.id}>
                {item.name}
              </option>
            );
          })}
        </select>
        <select>
          <option value="">请选择区县</option>
          {this.state.townList.map((item) => {
            return (
              <option key={item.id} value={item.id}>
                {item.name}
              </option>
            );
          })}
        </select>
      </div>
    );
  }
}
